// 2025/9/13
// O(1)时间插入、删除和获取随机元素

class RandomizedSet {
public:
    RandomizedSet() {
        srand((unsigned int)time(nullptr));        
    }
    
    bool insert(int val) {
        if(_map.count(val))
            return false;
        _map[val] = _nums.size();
        _nums.emplace_back(val);
        return true;
    }
    
    bool remove(int val) {
        if(!_map.count(val))
            return false;
        int pos = _map[val];
        int newval = _nums.back();
        _map.erase(val);
        if(pos != _nums.size() - 1)
        {
            _nums[pos] = newval;
            _map[newval] = pos;
        }
        _nums.erase(--_nums.end());
        return true;
    }
    
    int getRandom() {
        int n = rand() % _nums.size();
        return _nums[n];
    }
    vector<int> _nums;
    unordered_map<int, int> _map;
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet* obj = new RandomizedSet();
 * bool param_1 = obj->insert(val);
 * bool param_2 = obj->remove(val);
 * int param_3 = obj->getRandom();
 */